package com.insight.modules.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.insight.modules.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.insight.modules.system.service.*;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.system.base.controller.JeecgController;
import com.insight.common.system.query.QueryGenerator;
import com.insight.common.system.vo.LoginUser;
import com.insight.common.util.oConvertUtils;
import com.insight.modules.system.entity.SysDepartRole;
import com.insight.modules.system.entity.SysDepartRolePermission;
import com.insight.modules.system.entity.SysDepartRoleUser;
import com.insight.modules.system.entity.SysPermissionDataRule;
import com.insight.modules.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: 部门角色
 * @Author: jeecg-boot
 * @Date:   2020-02-12
 * @Version: V1.0
 */
 @Slf4j
 @Api(tags="部门角色")
 @RestController
 @RequestMapping("/sys/sysDepartRole")
 public class SysDepartRoleController extends JeecgController<SysDepartRole, ISysDepartRoleService> {

	 @Autowired
	 private ISysDepartRoleService sysDepartRoleService;

	 @Autowired
	 private ISysDepartRoleUserService departRoleUserService;

	 @Autowired
	 private ISysDepartPermissionService sysDepartPermissionService;

	 @Autowired
	 private ISysDepartRolePermissionService sysDepartRolePermissionService;

	 @Autowired
	 private ISysDepartService sysDepartService;

	 /**
	  * 分页列表查询部门角色
	  *
	  * @param sysDepartRole  查询条件封装实体
	  * @param pageNo         当前页码，默认1
	  * @param pageSize       每页条数，默认10
	  * @param deptId         部门ID，查询该部门下的角色
	  * @param req            HttpServletRequest对象，封装请求参数
	  * @return               分页角色列表结果封装
	  */
	 @ApiOperation(value="部门角色-分页列表查询", notes="部门角色-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<?> queryPageList(SysDepartRole sysDepartRole,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									@RequestParam(name="deptId",required=false) String deptId,
									HttpServletRequest req) {
		 // 通过QueryGenerator生成动态查询条件Wrapper
		 QueryWrapper<SysDepartRole> queryWrapper = QueryGenerator.initQueryWrapper(sysDepartRole, req.getParameterMap());

		 // 分页对象封装
		 Page<SysDepartRole> page = new Page<>(pageNo, pageSize);

		 // 这里注释掉的代码为多部门权限过滤逻辑，暂时不启用
//        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        List<String> deptIds = null;
//        if(oConvertUtils.isEmpty(deptId)){
//            if(oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals(CommonConstant.USER_IDENTITY_2) ){
//                deptIds = sysDepartService.getMySubDepIdsByDepId(user.getDepartIds());
//            }else{
//                return Result.ok(null);
//            }
//        }else{
//            deptIds = sysDepartService.getSubDepIdsByDepId(deptId);
//        }
//        queryWrapper.in("depart_id",deptIds);

		 // 仅查询指定部门的角色，确保用户只能看到当前部门数据
		 queryWrapper.eq("depart_id", deptId);

		 // 执行分页查询
		 IPage<SysDepartRole> pageList = sysDepartRoleService.page(page, queryWrapper);

		 // 返回查询结果
		 return Result.ok(pageList);
	 }

	 /**
	  * 添加部门角色
	  *
	  * @param sysDepartRole 需要添加的部门角色对象
	  * @return 添加结果
	  */
	 @ApiOperation(value="部门角色-添加", notes="部门角色-添加")
	 @PostMapping(value = "/add")
	 public Result<?> add(@RequestBody SysDepartRole sysDepartRole) {
		 sysDepartRoleService.save(sysDepartRole);
		 return Result.ok("添加成功！");
	 }

	 /**
	  * 编辑部门角色
	  *
	  * @param sysDepartRole 包含更新信息的部门角色实体
	  * @return 编辑结果
	  */
	 @ApiOperation(value="部门角色-编辑", notes="部门角色-编辑")
	 @PutMapping(value = "/edit")
	 public Result<?> edit(@RequestBody SysDepartRole sysDepartRole) {
		 sysDepartRoleService.updateById(sysDepartRole);
		 return Result.ok("编辑成功!");
	 }

	 /**
	  * 通过ID删除部门角色
	  *
	  * @param id 角色ID
	  * @return 删除结果
	  */
	 @AutoLog(value = "部门角色-通过id删除")
	 @ApiOperation(value="部门角色-通过id删除", notes="部门角色-通过id删除")
	 @DeleteMapping(value = "/delete")
	 public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		 sysDepartRoleService.removeById(id);
		 return Result.ok("删除成功!");
	 }

	 /**
	  * 批量删除部门角色
	  *
	  * @param ids 多个角色ID，逗号分隔
	  * @return 批量删除结果
	  */
	 @AutoLog(value = "部门角色-批量删除")
	 @ApiOperation(value="部门角色-批量删除", notes="部门角色-批量删除")
	 @DeleteMapping(value = "/deleteBatch")
	 public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		 this.sysDepartRoleService.removeByIds(Arrays.asList(ids.split(",")));
		 return Result.ok("批量删除成功！");
	 }

	 /**
	  * 通过ID查询部门角色详细信息
	  *
	  * @param id 角色ID
	  * @return 角色详细信息
	  */
	 @ApiOperation(value="部门角色-通过id查询", notes="部门角色-通过id查询")
	 @GetMapping(value = "/queryById")
	 public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		 SysDepartRole sysDepartRole = sysDepartRoleService.getById(id);
		 return Result.ok(sysDepartRole);
	 }

	 /**
	  * 获取指定部门下所有角色列表
	  *
	  * @param departId 部门ID
	  * @param userId   用户ID（目前未用到，可留待扩展）
	  * @return 指定部门角色列表
	  */
	 @RequestMapping(value = "/getDeptRoleList", method = RequestMethod.GET)
	 public Result<List<SysDepartRole>> getDeptRoleList(@RequestParam(value = "departId") String departId,
														@RequestParam(value = "userId") String userId) {
		 Result<List<SysDepartRole>> result = new Result<>();
		 // 查询该部门所有角色
		 List<SysDepartRole> deptRoleList = sysDepartRoleService.list(new LambdaQueryWrapper<SysDepartRole>()
				 .eq(SysDepartRole::getDepartId, departId));
		 result.setSuccess(true);
		 result.setResult(deptRoleList);
		 return result;
	 }

	 /**
	  * 给用户设置部门角色（添加角色授权）
	  *
	  * @param json 请求体，包含newRoleId, oldRoleId, userId
	  * @return 操作结果
	  */
	 @RequestMapping(value = "/deptRoleUserAdd", method = RequestMethod.POST)
	 public Result<?> deptRoleAdd(@RequestBody JSONObject json) {
		 String newRoleId = json.getString("newRoleId");
		 String oldRoleId = json.getString("oldRoleId");
		 String userId = json.getString("userId");
		 departRoleUserService.deptRoleUserAdd(userId, newRoleId, oldRoleId);
		 return Result.ok("添加成功！");
	 }

	 /**
	  * 根据用户ID查询其已设置的部门角色
	  *
	  * @param userId   用户ID
	  * @param departId 部门ID
	  * @return 用户对应的部门角色用户关联列表
	  */
	 @RequestMapping(value = "/getDeptRoleByUserId", method = RequestMethod.GET)
	 public Result<List<SysDepartRoleUser>> getDeptRoleByUserId(@RequestParam(value = "userId") String userId,
																@RequestParam(value = "departId") String departId) {
		 Result<List<SysDepartRoleUser>> result = new Result<>();
		 // 查询部门下所有角色
		 List<SysDepartRole> roleList = sysDepartRoleService.list(new QueryWrapper<SysDepartRole>()
				 .eq("depart_id", departId));
		 List<String> roleIds = roleList.stream().map(SysDepartRole::getId).collect(Collectors.toList());
		 // 查询用户在这些角色中的授权关系
		 List<SysDepartRoleUser> roleUserList = departRoleUserService.list(new QueryWrapper<SysDepartRoleUser>()
				 .eq("user_id", userId)
				 .in("drole_id", roleIds));
		 result.setSuccess(true);
		 result.setResult(roleUserList);
		 return result;
	 }

	 /**
	  * 查询权限数据规则列表
	  *
	  * @param permissionId 权限ID
	  * @param departId     部门ID
	  * @param roleId       角色ID
	  * @return 数据权限规则列表及角色已选中的规则ID
	  */
	 @GetMapping(value = "/datarule/{permissionId}/{departId}/{roleId}")
	 public Result<?> loadDatarule(@PathVariable("permissionId") String permissionId,
								   @PathVariable("departId") String departId,
								   @PathVariable("roleId") String roleId) {
		 // 查询部门对应权限的数据规则
		 List<SysPermissionDataRule> list = sysDepartPermissionService.getPermRuleListByDeptIdAndPermId(departId, permissionId);

		 if (list == null || list.isEmpty()) {
			 return Result.error("未找到权限配置信息");
		 } else {
			 Map<String,Object> map = new HashMap<>();
			 map.put("datarule", list);

			 // 查询角色菜单权限，判断是否已选数据规则
			 LambdaQueryWrapper<SysDepartRolePermission> query = new LambdaQueryWrapper<SysDepartRolePermission>()
					 .eq(SysDepartRolePermission::getPermissionId, permissionId)
					 .eq(SysDepartRolePermission::getRoleId, roleId);
			 SysDepartRolePermission sysRolePermission = sysDepartRolePermissionService.getOne(query);

			 if (sysRolePermission != null) {
				 String drChecked = sysRolePermission.getDataRuleIds();
				 if (oConvertUtils.isNotEmpty(drChecked)) {
					 // 去除末尾逗号
					 map.put("drChecked", drChecked.endsWith(",") ? drChecked.substring(0, drChecked.length()-1) : drChecked);
				 }
			 }
			 return Result.ok(map);
			 // TODO 以后按钮权限的查询也走这个请求，只需在map中多加两个key即可
		 }
	 }

	 /**
	  * 保存角色菜单关联的数据权限规则
	  *
	  * @param jsonObject 请求体，包含permissionId, roleId, dataRuleIds
	  * @return 保存结果
	  */
	 @PostMapping(value = "/datarule")
	 public Result<?> saveDatarule(@RequestBody JSONObject jsonObject) {
		 try {
			 if (jsonObject == null) {
				 return Result.error("请求参数为空");
			 }
			 String permissionId = jsonObject.getString("permissionId");
			 String roleId = jsonObject.getString("roleId");
			 String dataRuleIds = jsonObject.getString("dataRuleIds");
			 log.info("保存数据规则>> 菜单ID:{} 角色ID:{} 数据权限ID:{}", permissionId, roleId, dataRuleIds);
			 if (permissionId == null || roleId == null) {
				 return Result.error("菜单ID或角色ID为空");
			 }
			 LambdaQueryWrapper<SysDepartRolePermission> query = new LambdaQueryWrapper<SysDepartRolePermission>()
					 .eq(SysDepartRolePermission::getPermissionId, permissionId)
					 .eq(SysDepartRolePermission::getRoleId, roleId);
			 SysDepartRolePermission sysRolePermission = sysDepartRolePermissionService != null ? sysDepartRolePermissionService.getOne(query) : null;
			 if (sysRolePermission == null) {
				 return Result.error("请先保存角色菜单权限!");
			 } else {
				 sysRolePermission.setDataRuleIds(dataRuleIds);
				 if (this.sysDepartRolePermissionService != null) {
					 this.sysDepartRolePermissionService.updateById(sysRolePermission);
				 }
			 }
		 } catch (Exception e) {
			 log.error("SysRoleController.saveDatarule()发生异常：", e);
			 return Result.error("保存失败");
		 }
		 return Result.ok("保存成功!");
	 }

	 /**
	  * 导出部门角色数据到Excel
	  *
	  * @param request HTTP请求对象
	  * @param sysDepartRole 查询条件实体
	  * @return ModelAndView Excel视图对象
	  */
	 @RequestMapping(value = "/exportXls")
	 public ModelAndView exportXls(HttpServletRequest request, SysDepartRole sysDepartRole) {
		 return super.exportXls(request, sysDepartRole, SysDepartRole.class, "部门角色");
	 }

	 /**
	  * 从Excel导入部门角色数据
	  *
	  * @param request HTTP请求对象
	  * @param response HTTP响应对象
	  * @return 导入结果
	  */
	 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		 return super.importExcel(request, response, SysDepartRole.class);
	 }
 }

